package gherkinedit.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PlatformUI;

public class FilesystemUtils {

	public static File getCurrentProjectRootDirectory() {
		IEditorPart projectEditorPart = PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().getActiveEditor();

		if (projectEditorPart == null) {
			return null;
		} else {
			IFileEditorInput input = (IFileEditorInput) projectEditorPart
					.getEditorInput();
			IFile editorInput = input.getFile();
			IProject currentProject = editorInput.getProject();
			return currentProject.getLocation().toFile();
		}
	}

	public static List<File> getFilesByExtension(File directory,
			String extension) {
		List<File> allFiles = new ArrayList<>();
		File[] files = directory.listFiles();

		// Remember write permission
		boolean dirWritePermission = directory.canWrite();

		// Avoid race conditions by locking directory so no other program can
		// change the files
		directory.setReadOnly();

		for (File file : files) {
			if (file.isDirectory()) {
				allFiles.addAll(getFilesByExtension(file, extension));
			} else if (file.getName().endsWith("." + extension)) {
				allFiles.add(file);
			}
		}

		// Restore previous write permissions
		directory.setWritable(dirWritePermission);

		return allFiles;
	}
	
	public static List<String> getGherkinSentences(List<File> fileList) {
		List<String> gherkinAnnotations = new ArrayList<>();
		
		for (File file : fileList) {
			BufferedReader br;
			try {
				br = new BufferedReader(new FileReader(file));
				String line;
				while ((line = br.readLine()) != null) {
					if (line.trim().startsWith("@")) {
						gherkinAnnotations.add(line);
					}
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return gherkinAnnotations;
	}
	
	public static void saveStringAsFileInProject(String path, String filename, String fileContent) {
		String projectRoot;
		try {
			projectRoot = getCurrentProjectRootDirectory().getCanonicalPath();
			
			// Create directory if it does not exist
			File dir = new File (projectRoot + path);
			if (!dir.exists() && !dir.mkdirs()) {
		        throw new IOException("Unable to create " + dir.getAbsolutePath());
		    }
			
			fileContent.replaceAll("\n", System.getProperty("line.separator"));
			BufferedWriter out = new BufferedWriter(new FileWriter(projectRoot + path + filename));
			out.write(fileContent);
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String getFileContent(File file) {
	    StringBuilder fileContents = new StringBuilder((int)file.length());
	    Scanner scanner = null;
	    String lineSeparator = System.getProperty("line.separator");
	    try {
	    	scanner = new Scanner(file);
	    	while(scanner.hasNextLine()) {        
	            fileContents.append(scanner.nextLine() + lineSeparator);
	        }
	        return fileContents.toString();
	    } catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
	        scanner.close();
	    }
	    return "";
	}
}
